package com.view.bp.nettyService;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hzj
 * @date 2021/1/7 18:18
 * 解码器
 */
public class MyDecoderHandler extends MessageToMessageDecoder<ByteBuf> {
    private final Charset charset;
    private String data = "";

    public MyDecoderHandler() {
        this(Charset.defaultCharset());
    }

    public MyDecoderHandler(Charset charset) {
        if (charset == null) {
            throw new NullPointerException("charset");
        } else {
            this.charset = charset;
        }
    }
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        String s = msg.toString(this.charset).trim();
        Map map = checkData(s);
        Boolean flag = (Boolean) map.get("flag");
        if(flag){
            String data = map.get("data").toString();
            out.add(data);
        }else {
            return;
        }
    }
    private Map checkData(String msg){
        Map<String,Object> map = new HashMap<>();
        if((msg.startsWith("{") && msg.endsWith("}"))){
            map.put("data",msg);
            map.put("flag",true);
            return map;
        }
        data = data + msg;
        if(data.startsWith("{") && data.endsWith("}")){
            map.put("data",data);
            map.put("flag",true);
            return map;
        }
        map.put("flag",false);
        return map;
    }
}
